package com.ironman.sailboat.mobile.runner;

import cn.hutool.core.util.StrUtil;
import com.ironman.sailboat.mobile.computer.v2.TrainComputer;
import com.ironman.sailboat.mobile.context.MockConfigContext;
import com.ironman.sailboat.mobile.dataobject.td.Posture;
import com.ironman.sailboat.mobile.threadpool.ThreadPool;
import com.mybatisflex.core.row.Db;
import com.mybatisflex.core.row.Row;
import com.mybatisflex.core.row.RowUtil;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.noear.snack.ONode;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * description 传感器runner
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2023/12/15 9:48
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class PostureMockRunner extends AbstractMockRunner implements ApplicationListener<ApplicationReadyEvent> {

    final TrainComputer trainComputer;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        log.info("PostureOriginalRunner init start");
        ThreadPool.FIXED_EXECUTOR.submit(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                String sql = "SELECT ts, rol, yaw, pitch, posture_fill_type FROM `sailboat`.`training_data` WHERE tenant_code = ? AND level_id = ? AND m_hm_id = ? AND ts >=? AND ts <= ?";
                List<Row> rows = Db.selectListBySql(sql, MockConfigContext.fromTenantCode(), MockConfigContext.fromLevelId(), MockConfigContext.fromMHmId(), getSysTrainingProperties().getStartTime(), getSysTrainingProperties().getEndTime());
                Map<Date, Posture> dateMap = rows.stream().collect(Collectors.toMap(n -> n.getDate("ts"), n -> RowUtil.toEntity(n, Posture.class)));
                log.info("Posture rows: {}", rows.size());
                setStartAndEndTime(rows);
                COUNT_DOWN_LATCH.countDown();
                COUNT_DOWN_LATCH.await();
                traceBackData(date -> {
                    Posture posture = dateMap.get(date);
                    if (Objects.isNull(posture)) {
                        return null;
                    }
                    if (StrUtil.isBlank(posture.getPostureFillType())) {
                        return null;
                    }
                    boolean fillType = "1".equals(posture.getPostureFillType());
                    if (fillType) {
                        return null;
                    }
                    String[] z = posture.getYaw().split("\\|");
                    String[] x = posture.getRol().split("\\|");
                    String[] y = posture.getPitch().split("\\|");
                    for (int i = 0; i < x.length; i++) {
                        trainComputer.posture(
                                BigDecimal.valueOf(Double.parseDouble(z[i])).setScale(0, RoundingMode.HALF_UP).intValue(),
                                BigDecimal.valueOf(Double.parseDouble(x[i])).setScale(0, RoundingMode.HALF_UP).intValue(),
                                BigDecimal.valueOf(Double.parseDouble(y[i])).setScale(0, RoundingMode.HALF_UP).intValue(),
                                null);
                    }
                    String dataFormat = "{},{}";
                    return ONode.newObject().set("dataType", "posture").set("data", StrUtil.format(dataFormat, posture.getRol(), posture.getYaw()
                    ));
                });
            }
        });
        log.info("PostureOriginalRunner init finish");
    }
}
